package com.zzvcom.webapp.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.zzvcom.persist.model.admin.Image;
import com.zzvcom.service.admin.ImageManager;

@Controller
@Scope("prototype")
public class ImageGetter
{
	private InputStream imageStream;

	private String id;

	private ImageManager im;
	
	private static final String defaultImage="upload"+File.separator+"default.jpg";

	public String execute() throws Exception
	{
		File dfile=new File( ServletActionContext.getServletContext().getRealPath(defaultImage));		
		try
		{
			String ids[]=id.split("@");
			id=ids[0];
			Image image=im.get(id);;
			String relative=image.getPath().replaceAll("#","\\"+File.separator);
			
			if(ids.length==2)
			{
				String ext = relative.substring(relative.lastIndexOf("."));// 扩展名
				String pre = relative.substring(0, relative.lastIndexOf("."));// 扩展名以前
				relative=pre+"@"+ids[1]+ext;
			}
			String path = ServletActionContext.getServletContext().getRealPath(relative);
			//System.out.println(path);
			File file = new File(path);
			if (file.isFile())
			{
				imageStream = new FileInputStream(file);
			} else
			{
				imageStream = new FileInputStream(dfile);
			}
		} catch (Exception e)
		{
			imageStream = new FileInputStream(dfile);
			e.printStackTrace();
		}

		return "success";

	}

	public InputStream getImageStream()
	{
		return imageStream;
	}

	public void setImageStream(InputStream imageStream)
	{
		this.imageStream = imageStream;
	}

	public String getId()
	{
		return id;
	}

	public void setId(String id)
	{
		this.id = id;
	}

	public ImageManager getIm()
	{
		return im;
	}

	@Autowired
	public void setIm(ImageManager im)
	{
		this.im = im;
	}
}
